package com.suncky.frame.utils.permission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.suncky.frame.utils.activityresult.ActivityResultFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 动态权限工具类
 */
public class PermissionUtil {

    public static final int PERMISSION_REQUEST_CODE = 10005;
    private static final String TAG = "PermissionUtil";
    private final FragmentActivity activity;
    private PermissionFragment permissionFragment;

    public PermissionUtil(@NonNull FragmentActivity activity) {
        this.activity = activity;
        initFragment(activity);
    }

    public PermissionUtil(@NonNull Fragment fragment) {
        this.activity = fragment.requireActivity();
        initFragment(this.activity);
    }


    private void initFragment(FragmentActivity activity) {
        permissionFragment =  (PermissionFragment)activity.getSupportFragmentManager().findFragmentByTag(TAG);
        if (permissionFragment == null) {
            permissionFragment = new PermissionFragment();
            FragmentManager fragmentManager = activity.getSupportFragmentManager();
            fragmentManager.beginTransaction().add(permissionFragment, TAG).commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
    }

    /**
     * 请求单项权限
     * @param permission
     */
    public void requestPermission(@NonNull String permission) {
        requestPermission(PERMISSION_REQUEST_CODE, permission);
    }

    /**
     * 请求单项权限
     * @param permission
     * @param callback
     */
    public void requestPermission(@NonNull String permission, PermissionCallback callback) {
        requestPermission(PERMISSION_REQUEST_CODE, permission, callback);
    }

    /**
     * 请求单项权限
     *
     * @param requestCode
     * @param permission
     */
    public void requestPermission(int requestCode, @NonNull String permission) {
        requestPermission(requestCode, permission, null);
    }

    /**
     * 请求单项权限
     *
     * @param requestCode
     * @param permission
     */
    public void requestPermission(int requestCode, @NonNull String permission, PermissionCallback callback) {
        if (!isGranted(activity, permission)) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                /*
                 * 判断该权限请求是否已经被 Denied(拒绝)过。  返回：true 说明被拒绝过 ; false 说明没有拒绝过
                 * 如果用户在过去拒绝了权限请求，并在权限请求系统对话框中选择了 Don't ask again 选项，此方法将返回 false。
                 * 如果设备规范禁止应用具有该权限，此方法也会返回 false。
                 */
//                ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
                permissionFragment.requestPermissions(requestCode,new String[]{permission}, callback);
            } else {
//                ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
                permissionFragment.requestPermissions(requestCode,new String[]{permission}, callback);
            }
        } else {
            if (callback != null) {
                callback.onResult(requestCode, Collections.singletonList(permission), new ArrayList<String>());
            }
        }
    }

    /**
     * 请求多项权限
     * @param permissions
     */
    public void requestPermissions(@NonNull String[] permissions){
        requestPermissions(PERMISSION_REQUEST_CODE, permissions);
    }

    /**
     * 请求多项权限
     * @param permissions
     * @param callback
     */
    public void requestPermissions(@NonNull String[] permissions, PermissionCallback callback){
        requestPermissions(PERMISSION_REQUEST_CODE, permissions, callback);
    }

    /**
     * 请求多项权限
     * @param requestCode
     * @param permissions
     */
    public void requestPermissions(int requestCode, @NonNull String[] permissions){
        requestPermissions(requestCode, permissions, null);
    }

    /**
     * 请求多项权限
     * @param requestCode
     * @param permissions
     */
    public void requestPermissions(int requestCode, @NonNull String[] permissions, PermissionCallback callback){
        String[] denied = deniedPermissions(activity, permissions);
        if (denied.length > 0) {
//            ActivityCompat.requestPermissions(activity, denied, requestCode);
            permissionFragment.requestPermissions(requestCode, denied, callback);
        } else {
            if (callback != null) {
                callback.onResult(requestCode, Arrays.asList(permissions),new ArrayList<String>());
            }
        }
    }

    /**
     * 是否具有某项权限
     * @param context
     * @param permission
     * @return
     */
    public static boolean isGranted(Context context, String permission){
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 是否具有权限组中的所有权限
     * @param context
     * @param permissions
     * @return
     */
    public static boolean isAllGranted(Context context, String[] permissions){
        if (permissions == null || permissions.length == 0) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 筛选出为获取的权限
     * @param context
     * @param permissions
     * @return
     */
    public static String[] deniedPermissions(Context context, String[] permissions){
        if (permissions == null || permissions.length == 0) {
            return null;
        }
        List<String> denied=new ArrayList<>();
        for (String permission : permissions) {
            if (!isGranted(context,permission)) {
                denied.add(permission);
            }
        }
        return denied.toArray(new String[0]);
    }


    /**
     * 跳转设置页面
     */
    public static void launchSetting(Context context) {
        Intent i = new Intent();
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        i.setData(Uri.fromParts("package", context.getPackageName(), null));
        context.startActivity(i);
    }

    public interface PermissionCallback{
        void onResult(int requestCode, List<String> granted, List<String> denied);
    }
}
